Booleans


Booleans in JavaScript represent one of two values: true or false. They are often used in conditional testing.

1. Boolean Values

Boolean values can be created directly or as the result of comparisons:

let isTrue = true;
let isFalse = false;

let comparison = 10 > 5; // true
let equality = 10 === 10; // false  (compairs value and data type)
let equal = 10 == "10"; // true     (compairs value)
let inequality = 10 !== 5; // true

2. Boolean Object

Booleans can also be created using the Boolean object:

let boolObject = new Boolean(true);
console.log(boolObject); // Outputs: [Boolean: true]

3. Boolean Methods

The Boolean object has a few methods:

let bool = true;
console.log(bool.toString()); // Outputs: "true"
console.log(bool.valueOf()); // Outputs: true

4. Boolean Conversion

Values can be converted to booleans using the Boolean() function:

console.log(Boolean(0)); // Outputs: false
console.log(Boolean(1)); // Outputs: true
console.log(Boolean("")); // Outputs: false
console.log(Boolean("Hello")); // Outputs: true
console.log(Boolean(null)); // Outputs: false
console.log(Boolean(undefined)); // Outputs: false

5. Logical Operators

JavaScript provides several logical operators to work with booleans:

let a = true;
let b = false;

console.log(a && b); // Outputs: false
console.log(a || b); // Outputs: true
console.log(!a); // Outputs: false

6. Conditional Statements

Booleans are often used in conditional statements to control the flow of the program:

let isRaining = true;

if (isRaining) {
    console.log("Take an umbrella!");
} else {
    console.log("No need for an umbrella.");
}